package it.mbus.component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

/**
 * Class contains all the methods working with the remote service that manage the users
 * @author Fbihack
 *
 */
public class UserComponent
{
	
	private static final String urls="http://www.edev.it/ipuffisonoblu/service.php";
	 static BufferedReader reader =null;
		static 	StringBuilder stringBuilder = null;
	 static String line = null;
 
	/**
	 * MEthod logs user into remote system
	 */
	public static boolean login() {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urls);
		String result="";
		try {
		    // Add your data
			List<NameValuePair> nameValuePairs= new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("operation", "login"));
		    nameValuePairs.add(new BasicNameValuePair("uname", "giova"));
		    //We send pass plain but compare the MD5 hash on server side
		    nameValuePairs.add(new BasicNameValuePair("passw", "12345"));

		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		    // Execute HTTP Post Request
		    HttpResponse response = httpclient.execute(httppost);
		    HttpEntity entity = response.getEntity();
		    if(entity != null){
		    InputStream inputStream = entity.getContent();
		    result = convertStreamToString(inputStream);
		    }
		} catch (Exception e) {
		  	//there was an error, connectivity or anything else
			Log.d("ERR", e.getMessage());
		  }
		if(result.contains("1"))
		  	return true; //WE ARE LOGGED IN
		else
			//UNAME OR PASS IS WRONG
			return false;
	}

  
  public static String convertStreamToString(InputStream is) throws Exception{

  	reader = new BufferedReader(new InputStreamReader(is));

  stringBuilder = new StringBuilder();
  	
  	try {
  	while ((line = reader.readLine()) != null) {
  	stringBuilder.append(line + "\n");
  	}
  	} finally {
  	is.close();
  	}
  	return stringBuilder.toString();
  	}
}
